import {get, post, request} from './http.tsx';
import config from '../config/config.js';
import {BoardPage} from '../models/BoardPage.ts';
import {FileSystem} from 'react-native-file-access';
import {clearLogs, getLogs} from '@siteed/react-native-logger';
import AsyncStorage from '@react-native-async-storage/async-storage';

export function fetchData() {
  /// 模拟网络请求获取数��
  return new Promise((resolve, reject) => {
    get('/stadium/electronicClassCardApi/api/findElectronicClassCardBindApi', {
      electronicClassCardId: config.DEVICE_ID,
    })
      .then(res => {
        console.log(res.data);
        resolve(res.data as BoardPage);
      })
      .catch(err => {
        reject(err);
      });
  });
}

export function login(username: string, password: string) {
  return new Promise((resolve, reject) => {
    post(
      '/auth/auth/api/pcLoginApi?route=auth',
      {
        mobilePhone: username,
        password: password,
        loginType: '1',
      },
      true,
    )
      .then(res => {
        console.log(res);
        resolve(res.data);
      })
      .catch(err => {
        console.log(err);
        reject(err);
      });
  });
}

export function loginTeacherAPI(username: string, password: string) {
  return new Promise((resolve, reject) => {
    post(
      '/auth/auth/api/banPaiMemberLogin',
      {
        userName: username,
        password: password,
      },
      true,
    )
      .then(res => {
        console.log(res);
        resolve(res.data);
      })
      .catch(err => {
        console.log(err);
        reject(err);
      });
  });
}

export function uploadFile(uri: string) {
  return new Promise((resolve, reject) => {
    FileSystem.readFile(uri, 'base64').then(data => {
      console.log(data);
      const index = uri.lastIndexOf('/');
      post('/file/file/api/base64', {
        relative: 'interfaceSettings',
        appCode: 'interfaceSettings',
        sourceName: uri.substr(index + 1),
        fileStr: data,
      })
        .then(res => {
          console.log(res);
          resolve(res);
        })
        .catch(err => {
          reject(err);
        });
    });
  });
}

export function uploadSystemInfo(msg: string) {
  post('/stadium/electronicClassCardApi/api/banPaiMemoryInformationApi', {
    electronicClassCardId: config.DEVICE_ID,
    memoryInformation: msg,
  })
    .then(res => {
      console.log(res);
    })
    .catch(error => {
      console.log(error);
    });
}

export function uploadLoggers(completion: (arg0: boolean) => any) {
  const logs = getLogs();
  if (logs && logs.length > 0) {
    const logData = logs
      .map(log => `${new Date(log.timestamp).toLocaleString()}: ${log.message}`)
      .join('\n');
    AsyncStorage.getItem('updateInfo').then(res => {
      console.log('updateInfo:', res);
      try {
        let name = '';
        if (res) {
          const info = JSON.parse(res);
          name = info.name;
        }
        post(
          '/stadium/electronicClassCardApi/api/banPaiSysAppDeviceOperationLogApi?version=' +
            name +
            '&id=' +
            config.DEVICE_ID,
          {electronicClassCardId: config.DEVICE_ID, msg: logData},
        )
          .then(res => {
            clearLogs();
            completion && completion(true);
          })
          .catch(error => {
            console.log(error);
          });
      } catch (e) {
        console.log(e);
        completion && completion(false);
      }
    });
  } else {
    completion && completion(true);
  }
}
